package com.herench.bs.utils;

import java.util.Calendar;

/**
 * com.herench.bs.utils
 * Created by luoxiaoming on 2017/9/22/17:37
 * 根据身份证获取信息
 */
public class GetInformationByIdCardUtil {

    /**
     * 根据身份证获取年龄
     *
     * @param idCard 身份证号
     * @return 年龄
     */
    public String getAgeByIdCard(String idCard) {

        int age = 0;
        int leh = idCard.length();
        //将15位身份证号转换成18位
        if (leh == 15) {
            idCard = idCard.trim();
            StringBuffer stringBuffer = new StringBuffer(idCard);
            stringBuffer.insert(6, "19");
            idCard = stringBuffer.toString();
            char[] ch = idCard.toCharArray();
            int m = 0;
            int[] co = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
            char[] verCode = new char[]{'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};
            for (int i = 0; i < idCard.length(); i++) {
                m += (ch[i] - '0') * co[i];
            }
            int residue = m % 11;
            String addStr = String.valueOf(verCode[residue]);
            stringBuffer.append(addStr);
            idCard = stringBuffer.toString();
        }
        leh = idCard.length();
        if (leh == 18) {
            // 先截取到字符串中的年、月、日
            int selectYear = Integer.parseInt(idCard.substring(6, 10));
            int selectMonth = Integer.parseInt(idCard.substring(10, 12));
            int selectDay = Integer.parseInt(idCard.substring(12, 14));
            // 得到当前时间的年、月、日
            Calendar cal = Calendar.getInstance();
            int yearNow = cal.get(Calendar.YEAR);
            int monthNow = cal.get(Calendar.MONTH) + 1;
            int dayNow = cal.get(Calendar.DATE);

            // 用当前年月日减去生日年月日
            int yearMinus = yearNow - selectYear;
            int monthMinus = monthNow - selectMonth;
            int dayMinus = dayNow - selectDay;
            // 先大致赋值
            age = yearMinus;
            // 选了未来的年份
            if (yearMinus < 0) {
                age = 0;
                // 同年的，要么为1，要么为0
            } else if (yearMinus == 0) {
                // 选了未来的月份
                if (monthMinus < 0) {
                    age = 0;
                    // 同月份的
                } else if (monthMinus == 0) {
                    // 选了未来的日期
                    if (dayMinus < 0) {
                        age = 0;
                    } else {
                        age = 1;
                    }
                } else {
                    age = 1;
                }
            } else {
                // 当前月>生日月
                if (monthMinus < 0) {
                    //还未过生日
                    age = age - 1;
                    // 同月份的，再根据日期计算年龄
                } else if (monthMinus == 0) {
                    if (dayMinus < 0) {
                        //还未过生日
                        age = age - 1;
                    }
                }
            }
        }
        return Integer.toString(age);
    }
}